<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
  import { getHomeBannerAPI, getCategoryAPI, getHotPanelAPI } from '@/services/home'
  import type { XtxGuessInstance } from '@/types/component'
  import CustomNavbar from './components/CustomNavbar.vue'
  import CategoryPanel from './components/CategoryPanel.vue'
  import HotPanel from './components/HotPanel.vue'
  //导入骨架屏
  import PageSkeleton from './components/PageSkeleton.vue'
  // 轮播图数据
  const bannerList = ref<BannerItem[]>([])
  const getHomeBannerData = async () => {
    let res = await getHomeBannerAPI()
    bannerList.value = res.result
  }

  //前台分类数据
  const categoryList = ref<CategoryItem[]>([])
  const getCategoryData = async () => {
    let res = await getCategoryAPI()
    categoryList.value = res.result
  }

  // 热门分类数据
  const hotPanelList = ref<HotItem[]>([])
  const getHotPanelData = async () => {
    let res = await getHotPanelAPI()
    hotPanelList.value = res.result
  }

  //滚动触底
  const guessRef = ref<XtxGuessInstance>() // 获取猜你喜欢组件实例
  const onScrollToLower = () => {
    // 调用子组件方法
    guessRef.value?.getLikeListData()
  }

  // 下拉刷新
  const isTriggered = ref(false)
  const onRefresh = async () => {
    // 开启下拉刷新
    isTriggered.value = true
    //1 2 3挨个执行完成 才关闭
    // await getHomeBannerData()
    // await getCategoryData()
    // await getHotPanelData()

    guessRef.value?.resetData()
    //1 2 3同时执行, 都完成后关闭
    await Promise.all([getHomeBannerData(),getCategoryData(),getHotPanelData(),guessRef.value?.getLikeListData()])
    // 关闭下拉动画
    isTriggered.value = false
  }

  // 是否加载
  const isLoading = ref(false)
  onLoad(async () => {
    isLoading.value = true
    await Promise.all([getHomeBannerData(),getCategoryData(),getHotPanelData()])
    isLoading.value = false
  })


</script>

<template>
  <!-- 自定义导航栏 固定不动 -->
  <CustomNavbar />
  <!--
    scrolltolower 触底加载
    refresher-enabled 开启自定义下拉刷新
    refresher-triggered  设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
    @refresherrefresh 下拉刷新事件
  -->
  <scroll-view :refresher-triggered="isTriggered" @refresherrefresh="onRefresh" refresher-enabled @scrolltolower="onScrollToLower" class="scroll-view" scroll-y>
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading"/>
    <template v-else>
      <!-- 轮播 -->
      <XtxSwiper :list="bannerList"/>
      <!-- 前台分类 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotPanelList"/>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"/>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7!important;
  height: 100%;
  display: flex;
  flex-direction: column;
  .scroll-view {
    flex: 1;
  }
}
</style>
